var express = require('express');
var router = express.Router();
var logger = require('../common/logger').logger.getLogger("user");
var mysql_query = require('../common/mysql');
var httpresult = require('../common/response');
var md5 = require('md5');
var vertoken = require('../common/token');

router.post('/list', async function(req, res) {
    if (req.body.user_id === undefined || req.body.user_id === "") {
        return res.send(httpresult.sys_error("USER_ID_INVALID", "用户名无效"));
    }
    let [error, data] = await mysql_query("select course.title, course.name, course.course_id, " +
        "course.parent_id, course_parent.title as parent_title, course_parent.course_id as parent_id " +
        "from user_course left join course as course on user_course.course_id = course.course_id " +
        "left join course as course_parent on course.parent_id = course_parent.course_id where user_id = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(data));
});

/* GET users listing. */
router.post('/add', async function(req, res, next) {
    if (req.body.user_id === undefined || req.body.user_id === ""
        || req.body.course_id === undefined || req.body.course_id === "") {
        return res.send(httpresult.sys_error("用户id或课程id为空"));
    }

    // 子科目
    let [error, data] = await mysql_query("insert ignore  into user_course (user_id, course_id) value (?, ?)", [req.body.user_id, req.body.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }

    // 父科目
    [error, data] = await mysql_query("insert ignore into user_course (user_id, course_id) " +
        "value (?, (select parent_id from course where course_id = ?))",
        [req.body.user_id, req.body.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(data));
});

router.post('/delete', async function(req, res, next) {
    [error, data] = await mysql_query("delete from user_course where user_id = ? and course_id = ?",
        [req.body.user_id, req.body.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(data));

});

module.exports = router;
